<?php

namespace App\Controllers\Order;

use App\Models\Order\Order;
use App\Models\Order\PailebaoOrder;
use App\Models\User\User;
use App\Libs\DB\PailePdo;
use App\Models\Coupons\Coupons;
use App\Models\Coupons\CouponsMy;
use App\Libs\Log\Logger;
use App\Models\Goods\Goods;
use App\Models\Store\Store;

class PailePayOrder extends \App\Libs\Base\BaseAction
{

    protected function beforeRun()
    {
        parent::beforeRun();
        $this->needLogin = TRUE;
    }

    public function execute()
    {

        $uid = $this->session->user->id;
//        $uid = $this->request->getPost('uid');
        if (!$this->request->hasPost('order_sn')) {
            return \App\Libs\Views\Json::view(1, '缺少订单号！', null);
        }

        $orderSn = $this->request->getPost('order_sn');
        //检查订单是否可以支付
        $OrderOrCode = Order::checkOrder($uid, $orderSn);
        if (is_numeric($OrderOrCode)) {
            switch ($OrderOrCode) {
                //这里的失败，不需要暂时不需要展示，因为订单状态，用户请求订单页会刷新,不可支付的订单，用户一般找不到支付接口；
                case -10:
                    return \App\Libs\Views\Json::view(0, '支付失败，未找到对应订单!', ['subcode' => 39990, 'submsg' => '支付失败:未找到对应订单!']);
                    break;
                default:
                    return \App\Libs\Views\Json::view(0, '支付遇到问题：您的' . Order::getOrderText($OrderOrCode), ['subcode' => 40000 + (int)$OrderOrCode, 'submsg' => '支付遇到问题：您的' . Order::getOrderText($OrderOrCode)]);
                    break;
            }
        }
        $goods = $OrderOrCode->getRelated('App\Models\Goods\Goods');
        $buyInfo = [
            'subject' => '派乐宝消费：' . $goods->goods_name,
            'out_trade_no' => $OrderOrCode->order_sn,
            'goods_price' => $goods->goods_price,
            'goods_sale_price' => $goods->sale_price,
            'goods_buy_num' => $OrderOrCode->sum,
            'total_amount' => $OrderOrCode->price,   //订单总金额
        ];


        $operateInfo = json_encode($buyInfo);
        //开始事务
        PailePdo::begin();

        //开始派乐宝支付流程；
        //使用事务：有此条记录绝对是成功了；
        $newPaileOrder = new PailebaoOrder();
        $newPaileOrder->uid = $uid;
        //消费时，流水表的订单号，就是订单表的订单号，充值时，流水表的订单号是重新生成的cr开头
        $newPaileOrder->order_sn = $orderSn;
        $newPaileOrder->operate = 0; //tinyint:1:充值，0：消费
        $newPaileOrder->money_num = $OrderOrCode->price;
        //0:待支付，1，已经支付，
        $newPaileOrder->order_status = 1;  //由于使用了，事务，有此记录必定是付款成功的
        $newPaileOrder->operate_info = $operateInfo;
        if (!$newPaileOrder->create()) {
            PailePdo::rollback();//不一定需要
            return \App\Libs\Views\Json::view(0, '失败：系统繁忙,请稍后.', ['subcode' => 44444, 'submsg' => '失败：系统繁忙,请稍后.']);
        }
        //去扣款；
        $userModel = User::find([
            'conditions' => 'id=?1',
            'bind' => [1 => $uid]
        ]);
	//self::record($userModel->balance_num);
	//self::record($userModel->toArray());
        //检测余额足否
        if ((float)$userModel->balance_num < (float)$OrderOrCode->price) {
            PailePdo::rollback();
            return \App\Libs\Views\Json::view(0, '失败：余额不足', ['subcode' => 11111, 'submsg' => '支付失败：您的余额不足!']);
        }
        //扣款
        $userModel->balance = (float)((float)$userModel->balance_num - (float)$OrderOrCode->price);
        if (!$userModel->update()) {
            PailePdo::rollback();
            return \App\Libs\Views\Json::view(0, '失败：系统繁忙,请稍后..', ['subcode' => 44444, 'submsg' => '失败：系统繁忙,请稍后..']);
        }
	//self::record($userModel->balance_num);
	//self::record($userModel->toArray());
        //更改订单状态;
        $OrderOrCode->status = 1;
        $OrderOrCode->pay_method = 3;   //1.微信 2.支付宝 3.派乐宝
        $OrderOrCode->ptime = date('Y-m-d H:i:s');
        $OrderOrCode->buy_info = json_encode($buyInfo);
        if ($userModel->vip == '1' && $OrderOrCode->ticket_id == '0') {
            $oneCoupon = Coupons::getRandomCoupon()->toArray();
            //-----------------
            //返卷，填充卷的id
            $OrderOrCode->is_coupons = $oneCoupon['id'];
            //-----------------
            //在我的卷表里，加卷;
            $myNewCoupon = new CouponsMy();
            $myNewCoupon->cid = $oneCoupon['id'];
            $myNewCoupon->uid = $uid;
            $myNewCoupon->status = 0;  //0,待使用
            $source = '9';  //如果是数字提示了，错误
            $myNewCoupon->from_where = $source;  //来源未定
            $myNewCoupon->start_time = $oneCoupon['start_time'];
            $myNewCoupon->end_time = $oneCoupon['end_time'];
            $myNewCoupon->ctime = date('Y-m-d H:i:s', time());
            if (!$myNewCoupon->create()) {
                PailePdo::rollback();
                return \App\Libs\Views\Json::view(0, '失败：系统繁忙,请稍后...', ['subcode' => 44444, 'submsg' => '失败：系统繁忙,请稍后...']);
            }
            $OrderOrCode->get_ticket_id = $myNewCoupon->id;
        }

        //更改订单状态,
        if (!$OrderOrCode->update()) {
            PailePdo::rollback();
            return \App\Libs\Views\Json::view(0, '失败：系统繁忙,请稍后....', ['subcode' => 44444, 'submsg' => '失败：系统繁忙,请稍后....']);
        }
        //增加销量：
        Goods::addSaleNumber($OrderOrCode->gid);
        //提交事务;
        PailePdo::commit();
        return \App\Libs\Views\Json::view(0, '支付成功', ['subcode' => 0, 'submsg' => '支付成功', 'order_sn' => $orderSn,'balance'=>$userModel->balance]);
    }
    public static function record($post){
        $headMsg = "
";
        $msg = $headMsg . var_export($post, true);
        Logger::info('pailePay', $msg);
    }
	

}
